package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mapper.UserMapper;
import cn.tedu.egweibo1.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo1.pojo.dto.UserRegDTO;
import cn.tedu.egweibo1.pojo.entity.User;
import cn.tedu.egweibo1.pojo.vo.UserRegVO;
import org.apache.ibatis.annotations.ResultMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/v1/users/")
public class UserController {
@Autowired
private UserMapper userMapper;

    @PostMapping(value = "reg")
    public  int regUsers(@RequestBody UserRegDTO userRegDTO){
        System.out.println(userRegDTO);
       UserRegVO userRegVO= userMapper.selectUser(userRegDTO.getUsername());
       if (userRegVO!=null){
          return 2;
       }
        User user=new User();
        BeanUtils.copyProperties(userRegDTO,user);
        userMapper.insertUser(user);
        return 1;
    }
//登录接口
    @PostMapping(value = "login")
    public int loginUsers(@RequestBody UserLoginDTO userLoginDTO,HttpSession session){
        UserRegVO userRegVO=userMapper.selectUser(userLoginDTO.getUsername());
        if (userRegVO==null){
            return 3;
        }
        if((userRegVO.getPassword().equals(userLoginDTO.getPassword()))){
            session.setAttribute("user",userRegVO);
            return 1;
        }
        return 2;
    }

@GetMapping(value = "currentUser")
    public UserRegVO currentUsers(HttpSession session){

        UserRegVO userRegVO=(UserRegVO) session.getAttribute("user");
        return userRegVO;
}
@GetMapping(value = "logout")
    public void logout(HttpSession session){
       session.removeAttribute("user");
    }
}
